import React, { useContext } from 'react'
import './index.scss'
import { Context } from '../../App'
export default function MyCount({ goods_count, id }) {
  const changeGoodsCount = useContext(Context)
  const handleClick = (tag) => {
    // !#2 子组件调用传递过来的方法的同时并传递数据
    // 传递 ID
    // 传递期望看到的 goods_count
    let num
    if (tag === 'reduce') {
      // 减
      num = goods_count - 1
      // 点击减的时候小于 1 就返回
      if (num < 1) return
      // changeGoodsCount(id, goods_count - 1)
    } else if (tag === 'add') {
      // 加
      num = goods_count + 1
      // changeGoodsCount(id, goods_count + 1)
    }
    changeGoodsCount(id, num)
  }
  const handleChange = (e) => {
    const reg = /^[1-9]\d*$/
    if (reg.test(e.target.value)) changeGoodsCount(id, +e.target.value)
  }
  return (
    <div className='my-counter'>
      <button
        type='button'
        className='btn btn-light'
        onClick={() => handleClick('reduce')}
      >
        -
      </button>
      <input
        type='number'
        className='form-control inp'
        value={goods_count}
        onChange={handleChange}
      />
      <button
        type='button'
        className='btn btn-light'
        onClick={() => handleClick('add')}
      >
        +
      </button>
    </div>
  )
}
